package com.mti.zhpt.shared.core.configurer;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * zpf
 * 2020年1月7日
 *
 *  初始化 socket
 */
@Component
public class TCPSocket implements CommandLineRunner {

    private Socket socket = null;
    private OutputStream outputStream = null;
    private InputStream inputStream = null;

    @Override
    public void run(String... args) {
        new SocketThread().start();
    }

    /**
     * 开启一个县城
     */
    private class SocketThread extends Thread {

        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            sendHeartbeat();
            while (true) {
                try {
                    if (socket == null || socket.isClosed()) {
                        socket = new Socket("20.148.120.19", 502); // 连接socket
                        outputStream = socket.getOutputStream();
                    }
                    Thread.sleep(1000);
                    inputStream = socket.getInputStream();
                    int size = inputStream.available();
                    if (size <= 0) {
                        if ((System.currentTimeMillis() - startTime) > 3 * 10 * 1000) { // 如果超过30秒没有收到服务器发回来的信息，说明socket连接可能已经挂掉
                            socket.close(); // 这时候可以关闭socket连接
                            startTime = System.currentTimeMillis();
                        }
                        continue;
                    } else {
                        startTime = System.currentTimeMillis();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        socket.close();
                        inputStream.close();
                        outputStream.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 开启一个县城
     * 发送心跳包
     */
    public void sendHeartbeat() {
        try {
            String heartbeat = "HelloJava";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(10 * 1000);// 10s发送一次心跳
                            outputStream.write(heartbeat.getBytes());
                            outputStream.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void sendMessage(String message) {
        try {
            //将十六进制的字符串转换成字节数组
            byte[] cmdInfor2 = hexStrToBinaryStr(message);

            //利用流按照一定的操作，对socket进行读写操作
            outputStream.write(cmdInfor2);
            outputStream.flush();
        }catch (Exception e) {
            e.printStackTrace();
            try {
                socket.close();
                inputStream.close();
                outputStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 将十六进制的字符串转换成字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStrToBinaryStr(String hexString) {

        if (StringUtils.isEmpty(hexString)) {
            return null;
        }

        hexString = hexString.replaceAll(" ", "");

        int len = hexString.length();
        int index = 0;

        byte[] bytes = new byte[len / 2];

        while (index < len) {

            String sub = hexString.substring(index, index + 2);

            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);

            index += 2;
        }


        return bytes;
    }


}
